package com.example.xinli.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.xinli.dao.*;
import com.example.xinli.domain.entity.*;
import com.example.xinli.domain.entity.Record;
import com.example.xinli.domain.vo.*;
import com.example.xinli.job.WebSocketServer;
import com.example.xinli.service.IInterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.example.xinli.common.RedisConstants.INTER_LAST_TIME;
import static com.example.xinli.common.ToolContants.*;


@Service
@Slf4j
public class InterServiceImpl extends ServiceImpl<InterMapper, Inter> implements IInterService {

    @Autowired
    private InterMapper interMapper;

//    @Autowired
//    private QuestionMapper questionMapper;

    @Autowired
    private InterPageMapper interPageMapper;
    @Autowired
    private RecordMapper recordMapper;
    @Autowired
    private AnswerMapper answerMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ZidongsiweiMapper zidongsiweiMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private HuibidanganMapper huibidanganMapper;
    @Autowired
    private ZhengnianlianxiMapper zhengnianlianxiMapper;
    @Autowired
    private JiazhishouceMapper jiazhishouceMapper;
    @Autowired
    private JienalianxiMapper jienalianxiMapper;
    @Autowired
    private XingdongjihuaMapper xingdongjihuaMapper;
    @Autowired
    private YingduijihuaMapper yingduijihuaMapper;
    @Autowired
    private QingxucaijiMapper qingxucaijiMapper;

    @Override
    public ResponseBean getAllInterPages(int interId) {
        QueryWrapper<InterPage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("inter_id", interId);
        List<InterPage> interPageList = interPageMapper.selectList(queryWrapper);
        return ResponseBean.success(interPageList);
    }

    @Override
    public ResponseBean getInterPageById(int interId, int pageId) {
        QueryWrapper<InterPage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("inter_id", interId);
        queryWrapper.eq("page_id", pageId);
        InterPage interPage = interPageMapper.selectOne(queryWrapper);
        InterPageReturnVo interPageReturnVo = interPageToReturnVo(interPage);
        return ResponseBean.success(interPageReturnVo);
    }

    private InterPageReturnVo interPageToReturnVo(InterPage interPage) {
        InterPageReturnVo interPageReturnVo = new InterPageReturnVo(
                interPage.getPageId(),
                interPage.getInterId(),
                interPage.getImgUrl(),
                interPage.getNavbarTitle(),
                interPage.getOperationIcon(),
                interPage.getOperationText(),
                interPage.getSpecialPage(),
                interPage.getPageType()
        );
        if(interPage.getSlideImages() != null) {
            List<String> splitList = Arrays.asList(interPage.getSlideImages().split("%"));
            interPageReturnVo.setSlideImages(splitList);
        }
        if(interPage.getInputQuestions() != null) {
            List<String> splitList = Arrays.asList(interPage.getInputQuestions().split("%"));
            interPageReturnVo.setInputQuestions(splitList);
        }
        if(interPage.getInputPlaceHolders() != null) {
            List<String> splitList = Arrays.asList(interPage.getInputPlaceHolders().split("%"));
            interPageReturnVo.setInputPlaceholders(splitList);
        }
        if(interPage.getButtonUrls() != null) {
            List<String> splitList = Arrays.asList(interPage.getButtonUrls().split("%"));
            interPageReturnVo.setButtonUrls(splitList);
        }
        if(interPage.getAudioUrls() != null) {
            List<String> splitList = Arrays.asList(interPage.getAudioUrls().split("%"));
            interPageReturnVo.setAudioUrls(splitList);
        }
        if(interPage.getSelectUrls() != null) {
            List<String> splitList = Arrays.asList(interPage.getSelectUrls().split("%"));
            interPageReturnVo.setSelectUrls(splitList);
        }
        return interPageReturnVo;
    }

    @Override
    public ResponseBean getInterInfo(int interId) {
        Inter inter = interMapper.selectById(interId);
        return ResponseBean.success(inter);
    }

    @Override
    public ResponseBean getAllUserInter(String userId) {
        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<Record> interList = recordMapper.selectList(queryWrapper);
        return ResponseBean.success(interList);
    }

    @Override
    public ResponseBean getFinishedUserInter(String userId) {
        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("record_status", 1);
        List<Record> recordList = recordMapper.selectList(queryWrapper);
        return ResponseBean.success(recordList);
    }

    @Override
    public ResponseBean getUnfinishedUserInter(String userId) {
        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("record_status", 0);
        List<Record> recordList = recordMapper.selectList(queryWrapper);
        return ResponseBean.success(recordList);
    }

    @Override
    @Transactional
    public ResponseBean startInter(InterStartVo interStartVo) throws Exception {
        // 用户第一次进入某个干预时调用这个接口
        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        String userId = interStartVo.getUserId();
        int interId = interStartVo.getInterId();
        String startTime = interStartVo.getStartTime();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("inter_id", interId);
        queryWrapper.eq("record_status", 0);
        int recordId = 0;
        // 检查用户是否已经开始过本次干预
        Record recordIfExit = recordMapper.selectOne(queryWrapper);
        if(recordIfExit != null) {
            recordId = recordIfExit.getRecordId();
        }
        // 假如用户没有开始过本次干预
        if(recordIfExit == null) {
            Record record = new Record();
            record.setInterId(interId);
            record.setUserId(userId);
            record.setStartTime(startTime);
            record.setRecordStatus(0);
            int result = recordMapper.insert(record);
            if (result <= 0) {
                return ResponseBean.error(ResponseBeanEnum.ERROR);
            }
            recordId = record.getRecordId();
        }
        // 查询某次干预的全部页面
        QueryWrapper<InterPage> interPageQueryWrapper = new QueryWrapper<>();
        interPageQueryWrapper.eq("inter_id", interId);
        List<InterPage> interPageList = interPageMapper.selectList(interPageQueryWrapper);
        // 转换为 Vo 返回前端
        List<InterPageReturnVo> interPageReturnVoList = new ArrayList<>();
        for(InterPage interPage : interPageList) {
            InterPageReturnVo interPageReturnVo = interPageToReturnVo(interPage);
            interPageReturnVoList.add(interPageReturnVo);
        }
        InterStartReturnVo interStartReturnVo = new InterStartReturnVo(interId, recordId, interPageReturnVoList);

        return ResponseBean.success(interStartReturnVo);
    }

    @Override
    @Transactional
    public ResponseBean submitInter(InterSubmitVo interSubmitVo) {
        int interId = interSubmitVo.getInterId();
        String userId = interSubmitVo.getUserId();
        String inputPages = interSubmitVo.getInputPages();
        String inputContent = interSubmitVo.getInputContent();

        // 获取 recordId
        QueryWrapper<Record> queryWrapperRecord = new QueryWrapper<>();
        queryWrapperRecord.eq("inter_id", interId);
        queryWrapperRecord.eq("user_id", userId);
        queryWrapperRecord.eq("record_status", 0);
        Record record = recordMapper.selectOne(queryWrapperRecord);
        if (record == null) {
            return ResponseBean.error(ResponseBeanEnum.ERROR);
        }
        int recordId = record.getRecordId();
        // 更新 answer 表
        Answer answer = new Answer();
        answer.setUserId(userId);
        answer.setRecordId(recordId);
        answer.setInputContent(inputContent);
        answer.setInputPages(inputPages);
        answerMapper.insert(answer);

        // 已完成inter 更新 record 表
        record.setRecordStatus(1);
        record.setEndTime(interSubmitVo.getEndTime());
        recordMapper.update(record, queryWrapperRecord);

        if (interId == 1) {
            // 假如是干预1，将用户填写的内容加入到情绪采集工具表
            List<String> inputListInAInter = Arrays.asList(inputContent.split("#"));
            Qingxucaiji qingxucaiji = new Qingxucaiji();
            qingxucaiji.setUserId(userId);
            String date = interSubmitVo.getEndTime().split(" ")[0];
            qingxucaiji.setDate(date);
            qingxucaiji.setRecordId(recordId);
            for (int i : INTER1) {
                String inputInAPage = inputListInAInter.get(i);
                List<String> inputListInAPage = Arrays.asList(inputInAPage.split("%"));
                if (i == 4) {
                    qingxucaiji.setFeelingUrl(inputListInAPage.get(0));
                    if (inputListInAPage.get(0).endsWith("mood-happy.png")) {
                        qingxucaiji.setFeelingName("开心");
                    } else if (inputListInAPage.get(0).endsWith("mood-calm.png")) {
                        qingxucaiji.setFeelingName("平静");
                    } else if (inputListInAPage.get(0).endsWith("mood-angry.png")) {
                        qingxucaiji.setFeelingName("生气");
                    } else if (inputListInAPage.get(0).endsWith("mood-upset.png")) {
                        qingxucaiji.setFeelingName("沮丧");
                    } else if (inputListInAPage.get(0).endsWith("mood-anxious.png")) {
                        qingxucaiji.setFeelingName("焦虑");
                    } else if (inputListInAPage.get(0).endsWith("mood-sad.png")) {
                        qingxucaiji.setFeelingName("悲伤");
                    }
                } else if (i == 5) {
                    qingxucaiji.setRenzhi(inputListInAPage.get(0));
                    qingxucaiji.setXingwei(inputListInAPage.get(1));
                    qingxucaiji.setShengli(inputListInAPage.get(2));
                } else if (i == 6) {
                    qingxucaiji.setChansheng(inputListInAPage.get(0));
                    qingxucaiji.setYingdui(inputListInAPage.get(1));
                    qingxucaiji.setQixiao(inputListInAPage.get(2));
                }
            }
            qingxucaijiMapper.insert(qingxucaiji);
        } else if (interId == 2) {
            // 假如是干预2，将用户填写的内容加入到自动思维工具表
            List<String> inputListInAInter = Arrays.asList(inputContent.split("#"));
            Zidongsiwei zidongsiwei = new Zidongsiwei();
            zidongsiwei.setUserId(userId);
            String date = interSubmitVo.getEndTime().split(" ")[0];
            zidongsiwei.setDate(date);
            zidongsiwei.setRecordId(recordId);
            for (int i : INTER2) {
                String inputInAPage = inputListInAInter.get(i);
                List<String> inputListInAPage = Arrays.asList(inputInAPage.split("%"));
                if (i == 4) {
                    zidongsiwei.setQingjing(inputListInAPage.get(0));
                    zidongsiwei.setGanshou(inputListInAPage.get(1));
                    zidongsiwei.setZidongsiwei(inputListInAPage.get(2));
                    zidongsiwei.setHouxuyingxiang(inputListInAPage.get(3));
                } else if (i == 5) {
                    zidongsiwei.setSiweiName(inputListInAPage.get(0));
                } else if (i == 6) {
                    zidongsiwei.setMonsterUrl(inputListInAPage.get(0));
                } else if (i == 7) {
                    zidongsiwei.setRuheshibie(inputListInAPage.get(0));
                }
            }
            zidongsiweiMapper.insert(zidongsiwei);
        } else if (interId == 3) {
            // 假如是干预3，将用户填写的内容加入到回避档案工具表
            List<String> inputListInAInter = Arrays.asList(inputContent.split("#"));
            Huibidangan huibidangan = new Huibidangan();
            huibidangan.setUserId(userId);
            String date = interSubmitVo.getEndTime().split(" ")[0];
            huibidangan.setDate(date);
            huibidangan.setRecordId(recordId);
            for (int i : INTER3) {
                String inputInAPage = inputListInAInter.get(i);
                List<String> inputListInAPage = Arrays.asList(inputInAPage.split("%"));
                if (i == 4) {
                    huibidangan.setHuibiName(inputListInAPage.get(0));
                    huibidangan.setGanshou(inputListInAPage.get(1));
                    huibidangan.setQingjing(inputListInAPage.get(2));
                    huibidangan.setChangshi(inputListInAPage.get(3));
                    huibidangan.setYingxiang(inputListInAPage.get(4));
                    huibidangan.setZenme(inputListInAPage.get(5));
                }
            }
            huibidanganMapper.insert(huibidangan);
        } else if (interId == 4) {
            // 假如是干预4，将用户填写的内容加入到正念练习工具表
            List<String> inputListInAInter = Arrays.asList(inputContent.split("#"));
            Zhengnianlianxi zhengnianlianxi = new Zhengnianlianxi();
            zhengnianlianxi.setUserId(userId);
            String date = interSubmitVo.getEndTime().split(" ")[0];
            zhengnianlianxi.setDate(date);
            zhengnianlianxi.setRecordId(recordId);
            for (int i : INTER4) {
                String inputInAPage = inputListInAInter.get(i);
                List<String> inputListInAPage = Arrays.asList(inputInAPage.split("%"));
                if (i == 4) {
                    zhengnianlianxi.setQingjing(inputListInAPage.get(0));
                    zhengnianlianxi.setQingxu(inputListInAPage.get(1));
                    zhengnianlianxi.setBianhua(inputListInAPage.get(2));
                    zhengnianlianxi.setZenyang(inputListInAPage.get(3));
                    zhengnianlianxi.setGanshou(inputListInAPage.get(4));
                }
            }
            zhengnianlianxiMapper.insert(zhengnianlianxi);
        } else if (interId == 5) {
            // 假如是干预5，将用户填写的内容加入到接纳练习工具表
            List<String> inputListInAInter = Arrays.asList(inputContent.split("#"));
            Jienalianxi jienalianxi = new Jienalianxi();
            jienalianxi.setUserId(userId);
            String date = interSubmitVo.getEndTime().split(" ")[0];
            jienalianxi.setDate(date);
            jienalianxi.setRecordId(recordId);
            for (int i : INTER5) {
                String inputInAPage = inputListInAInter.get(i);
                List<String> inputListInAPage = Arrays.asList(inputInAPage.split("%"));
                if (i == 1) {
                    jienalianxi.setName(inputListInAPage.get(0));
                    jienalianxi.setQingjing(inputListInAPage.get(1));
                    jienalianxi.setGaosu(inputListInAPage.get(2));
                    jienalianxi.setXingdong(inputListInAPage.get(3));
                    jienalianxi.setZhidao(inputListInAPage.get(4));
                    jienalianxi.setGaosu(inputListInAPage.get(5));
                }
            }
            jienalianxiMapper.insert(jienalianxi);
        } else if (interId == 6) {
            // 假如是干预6，将用户填写的内容加入到价值手册工具表
            List<String> inputListInAInter = Arrays.asList(inputContent.split("#"));
            Jiazhishouce jiazhishouce = new Jiazhishouce();
            jiazhishouce.setUserId(userId);
            String date = interSubmitVo.getEndTime().split(" ")[0];
            jiazhishouce.setDate(date);
            jiazhishouce.setRecordId(recordId);
            for (int i : INTER6) {
                String inputInAPage = inputListInAInter.get(i);
                List<String> inputListInAPage = Arrays.asList(inputInAPage.split("%"));
                if (i == 1) {
                    jiazhishouce.setLingyu(inputListInAPage.get(0));
                } else if (i == 2) {
                    jiazhishouce.setMiaoshu(inputListInAPage.get(0));
                } else if (i == 3) {
                    jiazhishouce.setYitu(inputListInAPage.get(0));
                } else if (i == 4) {
                    jiazhishouce.setPingjia(inputListInAPage.get(0));
                } else if (i == 5) {
                    jiazhishouce.setShiqing(inputListInAPage.get(0));
                }
            }
            jiazhishouceMapper.insert(jiazhishouce);
        } else if (interId == 7) {
            // 假如是干预7，将用户填写的内容加入到行动计划工具表
            List<String> inputListInAInter = Arrays.asList(inputContent.split("#"));
            Xingdongjihua xingdongjihua = new Xingdongjihua();
            xingdongjihua.setUserId(userId);
            String date = interSubmitVo.getEndTime().split(" ")[0];
            xingdongjihua.setDate(date);
            xingdongjihua.setRecordId(recordId);
            xingdongjihua.setJihuaName(" ");
            for (int i : INTER7) {
                String inputInAPage = inputListInAInter.get(i);
                List<String> inputListInAPage = Arrays.asList(inputInAPage.split("%"));
                if (i == 1) {
                    xingdongjihua.setJihuaName(inputListInAPage.get(0));
                    xingdongjihua.setLingyu(inputListInAPage.get(1));
                    xingdongjihua.setJiazhi(inputListInAPage.get(2));
                    xingdongjihua.setYitu(inputListInAPage.get(3));
                } else if (i == 2) {
                    xingdongjihua.setMubiao(inputListInAPage.get(0));
                } else if (i == 3) {
                    xingdongjihua.setXingdong(inputListInAPage.get(0));
                    xingdongjihua.setXingdongTime(inputListInAPage.get(1));
                } else if (i == 4) {
                    xingdongjihua.setZhangai(inputListInAPage.get(0));
                } else if (i == 5) {
                    xingdongjihua.setYingdui(inputListInAPage.get(0));
                }
            }
            xingdongjihuaMapper.insert(xingdongjihua);
        } else if (interId == 99) {
            // 假如是结束部分，将用户填写的内容加入到应对计划工具表
            log.info(inputContent);
            List<String> inputListInAInter = Arrays.asList(inputContent.split("#"));
            log.info(inputListInAInter.toString());
            Yingduijihua yingduijihua = new Yingduijihua();
            yingduijihua.setUserId(userId);
            String date = interSubmitVo.getEndTime().split(" ")[0];
            yingduijihua.setDate(date);
            yingduijihua.setRecordId(recordId);
            yingduijihua.setJihuaName(" ");
            for (int i : INTER99) {
                String inputInAPage = inputListInAInter.get(i);
                List<String> inputListInAPage = Arrays.asList(inputInAPage.split("%"));
                if (i == 2) {
                    yingduijihua.setJihuaName(inputListInAPage.get(0));
                    yingduijihua.setQingjing(inputListInAPage.get(1));
                    yingduijihua.setCelue(inputListInAPage.get(2));
                    yingduijihua.setDuanqi(inputListInAPage.get(3));
                    yingduijihua.setChangqi(inputListInAPage.get(4));
                }
            }
            yingduijihuaMapper.insert(yingduijihua);
        }

        // 获取用户当前干预进度
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_id", userId);
        User user = userMapper.selectById(userId);
        int currProgress = user.getCurrProgress();

        if (currProgress == interId) {
            // 更新用户表的干预进度
            log.info("更新用户的干预进度");
            if (interId == 99 || interId == 100) {
                currProgress = 999;
            } else if (interId == 7) {
                currProgress = 99;
            } else if (interId == 15) {
                currProgress = 100;
            } else {
                currProgress++;
            }
            user.setCurrProgress(currProgress);
            userMapper.update(user, userQueryWrapper);

            // 将本次提交时间存入redis
            // redisTemplate.opsForValue().set(INTER_LAST_TIME + userId, System.currentTimeMillis());

            // 将三天后开启的干预 id(即上面的currProgress) 存入 redis, 键值: inter:userId -> currProgress

            if (interId != 0 && interId != 8 && interId != 7 && interId != 15 && interId != 99 && interId != 100 && interId != 999) {
//              redisTemplate.opsForValue().set("inter:" + userId, currProgress, 3, TimeUnit.DAYS); // 三天后该键过期
                redisTemplate.opsForValue().set("inter:" + userId, currProgress, 48, TimeUnit.HOURS); // 48小时后该键过期
            } else {
                redisTemplate.opsForValue().set("inter:" + userId, currProgress, 2, TimeUnit.MINUTES); // 两分钟后该键过期
            }

            return ResponseBean.success(currProgress);
        } else {
            return ResponseBean.success(currProgress);
        }
    }

    @Override
    public ResponseBean checkInterAvailability(String userId, int interId) {
        Object res = redisTemplate.opsForValue().get("inter:" + userId);
        if (res == null) {
            return ResponseBean.success("yes");
        } else {
            if (Integer.parseInt(String.valueOf(res)) != interId) {
                return ResponseBean.success("none");
            } else {
                return ResponseBean.success("yes");
            }
        }
    }

    @Override
    public ResponseBean getInterReadyTime(String userId, int interId) {
        Object res = redisTemplate.opsForValue().get("inter:" + userId);
        if (res != null) {
            if ((Integer.parseInt(String.valueOf(res)) != interId)) {
                return ResponseBean.success("none");
            }
            Long expireTimeSeconds = redisTemplate.getExpire("inter:" + userId, TimeUnit.SECONDS);
            if (expireTimeSeconds != null) {
                // 转换为小时单位
                long hoursToExpire = expireTimeSeconds / 3600;
                // 距离过期还有 hoursToExpire 小时
                return ResponseBean.success(hoursToExpire);
            }
        }
        return ResponseBean.success("none");
    }

    @Override
    public ResponseBean getUserGoal(String userId) {
        QueryWrapper<Record> recordQueryWrapper = new QueryWrapper<>();
        recordQueryWrapper.eq("user_id", userId);

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_id", userId);
        User user = userMapper.selectOne(userQueryWrapper);
        if (user.getGroupId() == 0) {
            recordQueryWrapper.eq("inter_id", 0);
        } else if (user.getGroupId() == 1) {
            recordQueryWrapper.eq("inter_id", 8);
        }

        recordQueryWrapper.orderByDesc("record_id").last("limit 1");
        Record record = recordMapper.selectOne(recordQueryWrapper);
        if (record != null) {
            QueryWrapper<Answer> answerQueryWrapper = new QueryWrapper<>();
            answerQueryWrapper.eq("user_id", userId);
            answerQueryWrapper.eq("record_id", record.getRecordId());
            Answer answer = answerMapper.selectOne(answerQueryWrapper);
            String content = answer.getInputContent();
            content = content.substring(0, content.length() - 2);
            String[] res = content.split("%#");
            return ResponseBean.success(res);
        }
        return ResponseBean.error(ResponseBeanEnum.ERROR);
    }
}

